﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;

namespace ReportGenerators.CongNo
{
    public partial class FrmTongHopCongNoKetHop : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopCongNoKetHop()
        {
            InitializeComponent();
        }

        private void FrmTongHopCongNoKetHop_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                dtThoiDiem.DateTime = System.DateTime.Now;
                #region cmbTaiKhoan
                DataView dvTaiKhoan = DanhMucTaiKhoan.GetByLoaiTaiKhoan(LoaiTaiKhoan.CongNo).DataView;
                cmbTaiKhoanNoPhaiThu.DataSource = dvTaiKhoan;
                cmbTaiKhoanNoPhaiThu.DisplayColumn = "Ten";
                cmbTaiKhoanNoPhaiThu.ValueColumn = "ID";
                cmbTaiKhoanNoPhaiThu.AddVisibleColumn("SoHieu", "Số hiệu");
                cmbTaiKhoanNoPhaiThu.AddVisibleColumn("Ten", "Tên");
                cmbTaiKhoanNoPhaiThu.EditValue = DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("PhaiThuKhachHang");

                cmbTaiKhoanNoPhaiTra.DataSource = dvTaiKhoan;
                cmbTaiKhoanNoPhaiTra.DisplayColumn = "Ten";
                cmbTaiKhoanNoPhaiTra.ValueColumn = "ID";
                cmbTaiKhoanNoPhaiTra.AddVisibleColumn("SoHieu", "Số hiệu");
                cmbTaiKhoanNoPhaiTra.AddVisibleColumn("Ten", "Tên");
                cmbTaiKhoanNoPhaiTra.EditValue = DanhMucCauHinhTaiKhoanMacDinh.Instance.GetTaiKhoanIDByTinhChat("PhaiTraNhaCungCap");
                #endregion
                dsTongHopCongNoKetHop.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucDoiTac().DataView.ToTable());
                gridControlDsDoiTac.DataSource = dsTongHopCongNoKetHop.DoiTuongNghiepVu;
                gridControl.DataSource = dsTongHopCongNoKetHop.Detail;
                dsTongHopCongNoKetHop.DoiTuongNghiepVu.ColumnChanged += new DataColumnChangeEventHandler(DoiTuongNghiepVu_ColumnChanged);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
            chkChooseAllDoiTac.Checked = true;
            FormatNumberInGridView(gridView);
        }

        void DoiTuongNghiepVu_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column.ColumnName == "Choose")
            {
                if (e.Row["Choose"] is bool && (bool)e.Row["Choose"] == false)
                    chkChooseAllDoiTac.Checked = false;
                if (e.Row["Choose"] is bool && (bool)e.Row["Choose"] == true)
                    chkUnChooseAllDoiTac.Checked = false;
            }
        }

        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            if (chkChooseAllDoiTac.Checked)
            {
                foreach (DataRow row in dsTongHopCongNoKetHop.DoiTuongNghiepVu.Rows)
                {
                    row["Choose"] = true;
                }
            }
        }
        private void chkUnChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUnChooseAllDoiTac.Checked)
            {
                foreach (DataRow row in dsTongHopCongNoKetHop.DoiTuongNghiepVu.Rows)
                {
                    row["Choose"] = false;
                }
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            BasicForms.FrmProgressBar.StartShowProgress();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                Guid taiKhoanPhaiThuID = (Guid)cmbTaiKhoanNoPhaiThu.EditValue;
                Guid taiKhoanPhaiTraID = (Guid)cmbTaiKhoanNoPhaiTra.EditValue;

                dsTongHopCongNoKetHop.Detail.Clear();
                int count = 0;

                DataRow[] selectedRows = dsTongHopCongNoKetHop.DoiTuongNghiepVu.Select("Choose = 1");
                foreach (DataRow row in selectedRows)
                {
                    BasicForms.FrmProgressBar.Status = string.Format("Đã xử lý {0}/{1}", count++, selectedRows.Length);
                    SoDuTheoDoiTuong noPhaiThu = SoDuTheoDoiTuong.CalculateFromDB(cmd, dtThoiDiem.DateTime, taiKhoanPhaiThuID, (Guid)row["ID"]);
                    SoDuTheoDoiTuong noPhaiTra = SoDuTheoDoiTuong.CalculateFromDB(cmd, dtThoiDiem.DateTime, taiKhoanPhaiTraID, (Guid)row["ID"]);
                    decimal phaiThu = noPhaiThu.DuNo - noPhaiThu.DuCo;
                    decimal phaiTra = noPhaiTra.DuCo - noPhaiTra.DuNo;
                    decimal soDu = phaiThu- phaiTra;
                    if ((soDu > 0 && chkHienThiPhaiThu.Checked) || (soDu < 0 && chkHienThiPhaiTra.Checked))
                    {
                        DoiTuongNghiepVu doiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)row["ID"]);
                        DataRow addedRow = dsTongHopCongNoKetHop.Detail.NewRow();
                        addedRow["MaDoiTac"] = doiTuongNghiepVu.Ma;
                        addedRow["TenDoiTac"] = doiTuongNghiepVu.Ten;
                        addedRow["PhaiThu"] = phaiThu;
                        addedRow["PhaiTra"] = phaiTra;
                        if (phaiThu >= phaiTra)
                        {
                            addedRow["PhaiThuSauBuTru"] = phaiThu - phaiTra;
                            addedRow["PhaiTraSauBuTru"] = 0;
                        }
                        else
                        {
                            addedRow["PhaiThuSauBuTru"] = 0;
                            addedRow["PhaiTraSauBuTru"] = phaiTra - phaiThu;
                        }
                        dsTongHopCongNoKetHop.Detail.Rows.Add(addedRow);
                    }
                }
                
                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string option1 = string.Format("Thời điểm {0}:{1} ngày {2}/{3}/{4}",
                                dtThoiDiem.DateTime.Hour, dtThoiDiem.DateTime.Minute,
                                dtThoiDiem.DateTime.Day, dtThoiDiem.DateTime.Month, dtThoiDiem.DateTime.Year);
            string option2 = string.Format("TK phải thu {0}. TK phải trả {1}", 
                                DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoanNoPhaiThu.EditValue).SoHieu,
                                DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoanNoPhaiTra.EditValue).SoHieu);

            PrintWithHeader(false, gridControl, true, true, "Tổng hợp công nợ phải thu phải trả", option1, option2);
        }
    }
}
